/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.customer.potentialcustomer.web;

import cn.knet.sp.ncrm.common.aspect.ExportExcelLock;
import cn.knet.sp.ncrm.common.config.Global;
import cn.knet.sp.ncrm.common.persistence.AjaxMessage;
import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.service.ExportSynService;
import cn.knet.sp.ncrm.common.service.ServiceException;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.web.BaseController;
import cn.knet.sp.ncrm.common.web.bind.annotation.FormModel;
import cn.knet.sp.ncrm.modules.customer.aftersalesservice.entity.PotentialAfterSalesService;
import cn.knet.sp.ncrm.modules.customer.importsupport.ImportService;
import cn.knet.sp.ncrm.modules.customer.importsupport.ImportUtil;
import cn.knet.sp.ncrm.modules.customer.importsupport.ImportVO;
import cn.knet.sp.ncrm.modules.customer.potentialadmingroup.entity.PotentialAdminGroup;
import cn.knet.sp.ncrm.modules.customer.potentialadmingroup.service.PotentialAdminGroupService;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.entity.PotentialCustomer;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.form.PotentialCustomerForm;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.service.PotentialCustomerService;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.vo.PotentialCustomerVo;
import cn.knet.sp.ncrm.modules.customer.potentialgroup.service.PotentialGroupService;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.user.service.SystemService;
import cn.knet.sp.ncrm.modules.sys.utils.ExcelUtils;
import cn.knet.sp.ncrm.modules.sys.utils.RegionUtils;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * 潜在客户主表Controller
 * @author gehaiyang
 * @version 2015-08-24
 */
@Controller
@RequestMapping ( value = "${adminPath}/customer/potentialCustomer" )
public class PotentialCustomerController extends BaseController {

	@Autowired
	private PotentialCustomerService potentialCustomerService;

	@Autowired
	private PotentialAdminGroupService potentialAdminGroupService;

	@Autowired
	private PotentialGroupService potentialGroupService;

	@Autowired
	private ImportService importService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private ExportSynService exportSynService;


	@ModelAttribute
	public PotentialCustomer get(@RequestParam ( required = false ) String id) {
		PotentialCustomer entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = potentialCustomerService.get(id);
		}
		if (entity == null) {
			entity = new PotentialCustomer();
		}
		return entity;
	}

	/**
	 * 跳转列表
	 * @param potentialCustomer
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月28日 上午10:21:12
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = {"list", ""} )
	public String list(PotentialCustomer potentialCustomer, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/customer/potentialcustomer/potentialCustomerAjaxList";
	}

	//@RequiresPermissions("customer:potentialCustomer:edit")
	@RequestMapping ( value = "save" )
	public String save(PotentialCustomerVo potentialCustomerVo, Model model, RedirectAttributes redirectAttributes) {
		/*if (!beanValidator(model, potentialCustomerVo)) {
			model.addAttribute("vo", potentialCustomerVo);
			return "modules/customer/potentialcustomer/detail/detailBasicForm";
		}*/
		potentialCustomerService.modifyBasicInfo(potentialCustomerVo);
		addMessage(redirectAttributes, "保存潜在客户信息成功");
		return "redirect:" + Global.getAdminPath() + "/customer/potentialCustomer/detailBasicInfo/?id=" + potentialCustomerVo.getId() + "&flag=" + potentialCustomerVo.getFlag();
	}

	/**
	 * 跳转详细页面
	 * @param model
	 * @return
	 * @author Gehaiyang
	 * @date 2015年9月10日 下午1:17:42
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "detail" )
	public String detail(PotentialCustomer potentialCustomer, Model model) {
		potentialCustomerService.modifyNoReadNum(potentialCustomer);
		model.addAttribute("id", potentialCustomer.getId());
		model.addAttribute("flag", 0);
		return "modules/customer/potentialcustomer/potentialCustomerDetail";
	}

	/**
	 * 跳转基本信息页面
	 * @param model
	 * @return
	 * @author Gehaiyang
	 * @date 2015年9月10日 下午1:17:59
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "detailBasicInfo" )
	public String detailBasicInfo(PotentialCustomerVo potentialCustomerVo, Model model) {
		PotentialCustomerVo vo = potentialCustomerService.getDetail(potentialCustomerVo);
		vo.setFlag(potentialCustomerVo.getFlag());
		model.addAttribute("vo", vo);
		return "modules/customer/potentialcustomer/detail/detailBasicInfo";
	}

	/**
	 * 修改基本信息
	 * @param model
	 * @return
	 * @author Gehaiyang
	 * @date 2015年9月10日 下午1:18:25
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "detailBasicForm" )
	public String detailBasicForm(PotentialCustomerVo potentialCustomerVo, Model model) {
		PotentialCustomerVo vo = potentialCustomerService.getDetail(potentialCustomerVo);
		vo.setFlag(potentialCustomerVo.getFlag());
		model.addAttribute("vo", vo);
		return "modules/customer/potentialcustomer/detail/detailBasicForm";
	}


	/**
	 * 删除数据
	 * @param ids
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月28日 上午10:20:49
	 */
	@RequiresPermissions ( "customer:potentialCustomer:delete" )
	@RequestMapping ( value = "delete" )
	@ResponseBody
	public AjaxMessage delete(String[] ids) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ids.length == 0) {
				ajaxMessage.makeError("请选择需要删除的数据");
				return ajaxMessage;
			}
			PotentialCustomer potentialCustomer = null;
			for (int i = 0; i < ids.length; i++) {
				potentialCustomer = new PotentialCustomer(ids[i]);
				potentialCustomerService.delete(potentialCustomer);
			}
			ajaxMessage.setMessage("删除成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("删除数据出现问题，请稍后再试");
		}
		return ajaxMessage;
	}
	/**
	 * 回收数据
	 * @param ids
	 * @return
	 * @author jief
	 * @date 2016年9月8日 下午10:20:49
	 */
	@RequiresPermissions ( "customer:potentialCustomer:edit" )
	@RequestMapping ( value = "recovery" )
	@ResponseBody
	public AjaxMessage recovery(String[] ids) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		List<PotentialCustomer> customerList = new ArrayList<PotentialCustomer>();
		try {
			if (ids.length == 0) {
				ajaxMessage.makeError("请选择需要回收的数据");
				return ajaxMessage;
			}
			//add by jief 20170214 start
			for (int i = 0; i < ids.length; i++) {
				PotentialCustomer customer = potentialCustomerService.get(ids[i]);
				customer.setExecutorId(null);//执行人ID
				customer.setExecutorName(null);
				customer.setDistStatus("UNDISTED");//分配状态
				customerList.add(customer);
			}
			//回收数据
			User user=UserUtils.getUser();
			importService.newRecover(user,customerList);
			//add by jief 20170214 end 
//			PotentialCustomer potentialCustomer = null;
//			for (int i = 0; i < ids.length; i++) {
//				potentialCustomer = new PotentialCustomer(ids[i]);
//				potentialCustomer.setDistStatus("UNDISTED");
//				
//				potentialCustomerService.recovery(potentialCustomer);
//			}
			ajaxMessage.setMessage("数据回收成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("数据回收出现问题，请稍后再试");
		}
		return ajaxMessage;
	}
	
	/**
	 * 获取列表数据
	 * @param potentialCustomer
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月27日 下午4:00:44
	 */
//	@RequiresPermissions ( "customer:potentialCustomer:view" )
//	@RequestMapping ( value = "listAjaxData" )
//	@ResponseBody
//	public Page<PotentialCustomer> listAjaxData(PotentialCustomer potentialCustomer, HttpServletRequest request, HttpServletResponse response, Model model) {
//		//判断数据是否第一次加载，第一次加载默认查询未分配状态的数据
//		if (!request.getParameterMap().containsKey("distStatus")) {
//			potentialCustomer.setDistStatus("UNDISTED");
//		}
//		potentialCustomer.setRecordVisibilityRule("public");
//		return potentialCustomerService.findPage(new Page<PotentialCustomer>(request, response), potentialCustomer);
//	}

	/**
	 * 获取列表数据
	 * @param potentialCustomerform
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author jief
	 * @date 2016年9月11日 上午10:00:44
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "listAjaxData" )
	@ResponseBody
	public Page<PotentialCustomer> listAjaxData(PotentialCustomer potentialCustomerform, HttpServletRequest request, HttpServletResponse response, Model model) {
		// TODO 根据用户类型返回不同的数据集
		//判断数据是否第一次加载，第一次加载默认查询未分配状态的数据
		if (!request.getParameterMap().containsKey("distStatus")) {
			potentialCustomerform.setDistStatus("UNDISTED");
		}
		potentialCustomerform.setRecordVisibilityRule("public");
		//add jief 20170208
		User user=UserUtils.getUser();
		String userFlag = user.getUserType();
		if("2".equals(userFlag) || "4".equals(userFlag)){
			// 返回此用户及下级数据
			potentialCustomerform.setVisibilityUserId(user.getId());
			return potentialCustomerService.findSubPage(new Page<PotentialCustomer>(request, response), potentialCustomerform);
		}
//		logger.info("PotentialCustomerForm="+potentialCustomerform.toString());
		return potentialCustomerService.findPage(new Page<PotentialCustomer>(request, response), potentialCustomerform);
	}
	/**
	 * 跳转分配页面
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月27日 下午4:00:32
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "jumpToDistIndex" )
	public String jumpToDistIndex() {
		return "modules/customer/potentialcustomer/potentialCustomerDistIndex";
	}

	/**
	 * 获取用户信息
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月27日 下午4:00:19
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "userAjaxData" )
	@ResponseBody
	public Page<User> userAjaxData(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		return systemService.findUser(new Page<User>(request, response), user);
	}

	/**
	 * 分配数据
	 * @param ids
	 * @param userIds
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月27日 下午4:00:07
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "distData" )
	@ResponseBody
	public AjaxMessage distData(String[] ids, String[] userIds) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ids.length == 0) {
				ajaxMessage.makeError("请选择需要分配的数据");
				return ajaxMessage;
			}
			if (userIds.length == 0) {
				ajaxMessage.makeError("请选择需要分配的人员");
				return ajaxMessage;
			}
			
//			potentialCustomerService.distData(ids, userIds);
			User user=UserUtils.getUser();
			potentialCustomerService.newDistData(user,ids, userIds);
			ajaxMessage.setMessage("数据分配成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("分配数据出现问题，请稍后再试");
		}
		return ajaxMessage;
	}

	/**
	 * 数据分组
	 * @param groupId
	 * @param ids
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月29日 下午4:53:42
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "adminGroupData" )
	@ResponseBody
	public AjaxMessage adminGroupData(String groupId, String[] ids) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ids.length == 0) {
				ajaxMessage.makeError("请选择需要分组的数据");
				return ajaxMessage;
			}
			if (StringUtils.isBlank(groupId)) {
				ajaxMessage.makeError("请选择分组");
				return ajaxMessage;
			}
			potentialCustomerService.adminGroupData(ids, groupId);
			ajaxMessage.setMessage("数据分组成功");
		} catch (ServiceException se) {
			ajaxMessage.makeError(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("数据分组出现问题，请稍后再试");
		}
		return ajaxMessage;
	}

	/**
	 * 删除分组
	 * @param potentialAdminGroup
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月29日 下午4:54:29
	 */
	//@RequiresPermissions("customer:potentialAdminGroup:edit")
	@RequestMapping ( value = "deleteAdminGroup" )
	@ResponseBody
	public AjaxMessage deleteAdminGroup(PotentialAdminGroup potentialAdminGroup) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (StringUtils.isNotBlank(potentialAdminGroup.getId())) {
				potentialCustomerService.deleteAdminGroup(potentialAdminGroup);
				ajaxMessage.setMessage("删除分组成功");
			} else {
				ajaxMessage.makeError("删除分组失败");
			}
		} catch (ServiceException se) {
			logger.error(se.getMessage(), se);
			ajaxMessage.makeError(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("删除分组异常，请稍后重试");
		}
		return ajaxMessage;
	}

	/**
	 * 跳转批量修改页面
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月30日 下午6:06:05
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "jumpToBatchEdit" )
	public String jumpToBatchEdit() {
		return "modules/customer/potentialcustomer/potentialCustomerBatchEdit";
	}

	/**
	 * 执行批量修改
	 * @return
	 * @author Gehaiyang
	 * @date 2015年8月30日 下午6:06:05
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "batchEditData" )
	@ResponseBody
	public AjaxMessage batchEditData(@FormModel("customer")PotentialCustomer potentialCustomer,
									 @FormModel("afterSalesService")PotentialAfterSalesService afterSalesService) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ArrayUtils.isNotEmpty(potentialCustomer.getIds())) {
				potentialCustomerService.batchEditData(potentialCustomer, afterSalesService);
				ajaxMessage.setMessage("批量修改成功");
			} else {
				ajaxMessage.makeError("请选择需要修改的数据");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("批量修改出现异常，请稍后重试");
		}
		return ajaxMessage;
	}

	/**
	 * 合并数据
	 * @param potentialCustomer
	 * @return
	 * @author Gehaiyang
	 * @date 2015年9月1日 下午3:38:55
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "mergerData" )
	@ResponseBody
	public AjaxMessage mergerData(PotentialCustomer potentialCustomer) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		try {
			if (ArrayUtils.isEmpty(potentialCustomer.getIds())) {
				ajaxMessage.makeError("请选择需要合并的数据");
			} else if (StringUtils.isBlank(potentialCustomer.getId())) {
				ajaxMessage.makeError("请选择主数据");
			} else {
				potentialCustomerService.mergerData(potentialCustomer);
				ajaxMessage.setMessage("合并成功");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("合并出现异常，请稍后重试");
		}
		return ajaxMessage;
	}

	/**
	 * 导出数据
	 * @param potentialCustomer
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author Gehaiyang
	 * @date 2015年9月2日 上午8:21:56
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "exportData" )
	@ExportExcelLock ( lockerId = "potentialCustomerExport" )
	public String exportData(PotentialCustomer potentialCustomer, HttpServletRequest request, HttpServletResponse response, Model model) {
		potentialCustomer.setRecordVisibilityRule("public");
		//System.err.println("SQL 查询开始:"+DateUtils.getTime());
		Page<PotentialCustomer> page = new Page<PotentialCustomer>(request, response);
		page.setPageSize(10000);
		//add by jeif start 根据用户类型查询
		String userFlag = UserUtils.getUser().getUserType();
		if("2".equals(userFlag) || "4".equals(userFlag)){
			// 返回此用户及下级数据
			page=potentialCustomerService.findSubPage(page, potentialCustomer);
		}else{
			page = potentialCustomerService.findPage(page,potentialCustomer);
		}
		//end
		List<PotentialCustomer> list = page.getList();
		//List<PotentialCustomer> list = potentialCustomerService.findList(potentialCustomer);
		//System.err.println("SQL 查询结束:"+DateUtils.getTime());
		ExcelUtils.Sheet sheet = new ExcelUtils.Sheet();
		sheet.setName("潜在客户管理导出表");
		sheet.setList(list);
		sheet.setRows(false);
		sheet.addColumn("重复数据（新）", "repeatAndNew").addColumn("更新时间", "lastUpdated", "date", "yyyy-MM-dd HH:mm:ss").addColumn("公司名称", "corporationName").addColumn("意向产品", "targetProductsText").addColumn("客户状态", "customerStatus").addColumn("上次客户状态", "lastCustomerStatus").addColumn("分配状态", "distStatusText").addColumn("来源设备", "mobileOrPcText").addColumn("预约回访时间", "dateAppointment").addColumn("是否联系", "contact");
		return exportSynService.exportSyn(sheet, model);
	}

	/**
	 * 查询被合并的数据
	 * @param potentialCustomer
	 * @return
	 * @author Gehaiyang
	 * @date 2015年9月7日 下午2:03:36
	 */
	@RequestMapping ( "listMergerData" )
	@ResponseBody
	public Page<PotentialCustomer> listMergerData(PotentialCustomer potentialCustomer) {
		Page<PotentialCustomer> page = new Page<>();
		page.setOrderBy("a.date_created desc");
		potentialCustomer.setPage(page);
		page.setList(potentialCustomerService.findList(potentialCustomer));
		return page;
	}

	/**
	 * 分解数据
	 * @return the ajax message
	 * @author fengyapeng
	 * @since 2015 /08/31 17:43:35
	 */
	@RequestMapping ( "resolveData" )
	@ResponseBody
	public AjaxMessage resolveData(String id, Integer flag) {
		try {
			AjaxMessage ajaxMessage = AjaxMessage.success("分解数据成功");
			PotentialCustomer potentialCustomer = get(id);
			potentialCustomer.setFlag(flag);
			potentialCustomerService.resolvePotentialCustomer(potentialCustomer);
			return ajaxMessage;
		} catch (Exception e) {
			logger.error("分解数据出现错误", e);
			return AjaxMessage.error("分解数据失败");
		}
	}

	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "import/form" )
	public String importForm(ImportVO vo, Model model) {
		int userWeight = 40;
		String userFlag = UserUtils.getUser().getUserType();

		if ("1".equals(userFlag)) {
			userWeight = 90;
		} else if ("2".equals(userFlag)) {
			userWeight = 60;
		}

		model.addAttribute("customer", vo);
		model.addAttribute("userWeight", userWeight);
		return "modules/customer/potentialcustomer/potentialCustomerImportForm";
	}


	/**
	 * 添加用户数据
	 * @param vo
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions ( "customer:potentialCustomer:edit" )
	@RequestMapping ( value = "import/save" )
	public String importSave(ImportVO vo, Model model, RedirectAttributes redirectAttributes) {
		/*if (!beanValidator(model, vo)) {
			model.addAttribute("vo", vo);
			return "modules/customer/potentialcustomer/potentialCustomerImportForm";
		}*/
		boolean flag = true;
		String errorMsg = "添加成功";

		//根据用户角色，判断是否合并
		List<ImportVO> voList = new ArrayList<ImportVO>();
		if (StringUtils.isBlank(vo.getWeight() + "")) {
			vo.setWeight(0);//权重
		}
		vo.setVersion(Long.parseLong("0"));//版本
		vo.setSource("系统添加");
		vo.setDateCreated(new Date());//创建时间
		vo.setLastUpdated(new Date());//最后更新时间
		vo.setDistStatus("UNDISTED");//分配状态
		vo.setMergerNum(0);//合并数量
		vo.setMobileOrPc("pc");//设备来源
		vo.setNoReadMergerNum(0);//未读合并数量
		vo.setVisitNum(0);//回访次数
		vo.setRecordVisibilityRule("public");//公有私有
		vo.setVisibilityUserId(UserUtils.getUser().getId());//持有人ID
		//仅个人导入需要初始化执行人ID
		//vo.setExecutorId(UserUtils.getUser().getId());//执行人ID
		vo.setDelFlag("0");//删除标识

		voList.add(vo);

		int userWeight = 40;
		String userFlag = UserUtils.getUser().getUserType();

		if ("1".equals(userFlag)) {
			userWeight = 90;
		} else if ("2".equals(userFlag)) {
			userWeight = 60;
		}

		int successNum = voList.size();
		int mergerNum = 0;
		try {
			mergerNum = importService.save(voList, userWeight, true, "ADD");
		} catch (Exception e) {
			flag = false;
			errorMsg = "请检测导入的客户字段是否正确或者联系管理员";
			e.printStackTrace();
		}
		model.addAttribute("successNum", successNum);
		model.addAttribute("mergerNum", mergerNum);
		model.addAttribute("flag", flag);
		model.addAttribute("errorMsg", errorMsg);

		return "modules/customer/potentialcustomer/potentialCustomerImportResult";
	}


	/**
	 * 下载导入模板
	 * @return
	 * @throws Exception
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "import/template" )
	public ResponseEntity<byte[]> importTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {

		File templateFile = new File(request.getSession().getServletContext().getRealPath("/static/templates/customer-of-import-templates.xlsx"));

		HttpHeaders headers = new HttpHeaders();
		//获取User-Agent
		String agent = request.getHeader("User-Agent");
		if (org.apache.commons.lang3.StringUtils.isNotBlank(agent) && agent.toLowerCase().contains("linux")) {
			//解决Linux系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入模板.xlsx".getBytes("UTF-8"), "ISO8859-1"));
		} else {
			//解决Windows系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入模板.xlsx".getBytes("GBK"), "ISO8859-1"));
		}
		//导出office2010文件，后缀格式.xlsx
		headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(templateFile), headers, HttpStatus.CREATED);

	}

	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions ( "customer:potentialCustomer:edit" )
	@RequestMapping ( value = "import", method = RequestMethod.POST )
	public String importFile(MultipartFile file, String realAdminGroupId, RedirectAttributes redirectAttributes, Model model) throws Exception {
		int successNum = 0;
		int mergerNum = 0;
		int maxsize = 8 * 1024 * 1024;//8M
		int maxRowNum = 10000;//1万条数据
		boolean flag = true;
		String errorMsg = "导入客户基本信息出现错误,请下载校验后的文件进行查看";

		if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equalsIgnoreCase(file.getContentType()) || "application/wps-office.xlsx".equalsIgnoreCase(file.getContentType())) {

			if (file.getSize() <= maxsize) {

				XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream());
				// Read the Sheet
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
				long begin = System.currentTimeMillis();
				int lastRowNum = xssfSheet.getLastRowNum();

				if (lastRowNum - 2 <= maxRowNum) {
					// Read the Row
					for (int rowNum = 3; rowNum <= lastRowNum; rowNum++) {
						XSSFRow xssfRow = xssfSheet.getRow(rowNum);

						if (null == xssfRow) {
							xssfRow = xssfSheet.createRow(rowNum);
							ImportUtil.setStyle(xssfWorkbook, xssfRow);
							flag = false;
							continue;
						} else {
							ImportUtil.setRowDefaultStyle(xssfWorkbook, xssfRow);
						}
						String corporationName = ImportUtil.getValue(xssfRow.getCell(0));
						if (!ImportUtil.checkRequired(corporationName)) {
							xssfRow.createCell(0);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(0));
							flag = false;

							/**
							 * 	修改，超过100字符自动截取
							 *	shishouyang
							 *	2015-10-26
							 */
						} /*else if (corporationName.length() > 50) {
							xssfRow.getCell(0);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(0));
							flag = false;
						}*/
						String contactorName = ImportUtil.getValue(xssfRow.getCell(1));
						if (!ImportUtil.checkRequired(contactorName)) {
							xssfRow.createCell(1);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(1));
							flag = false;
							/**
							 * 	联系人长度验证由原来的不超过10变为不超过100
							 * 	再次修改，超过100字符自动截取
							 *	shishouyang
							 *	2015-10-26
							 */
						} /*else if (contactorName.length() > 100) {
							xssfRow.getCell(1);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(1));
							flag = false;
						}*/
						/**
						 * 	取消手机格式验证和电话格式验证
						 *	shishouyang
						 *	2015-10-26
						 */
						/*if (StringUtils.isNotBlank(ImportUtil.getValue(xssfRow.getCell(2))) && !ImportUtil.checkMobile(ImportUtil.getValue(xssfRow.getCell(2)))) {
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(2));
							flag = false;
						}
						if (StringUtils.isNotBlank(ImportUtil.getValue(xssfRow.getCell(3))) && !ImportUtil.checkPhone(ImportUtil.getValue(xssfRow.getCell(3)))) {
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(3));
							flag = false;
						}*/
						if (StringUtils.isBlank(ImportUtil.getValue(xssfRow.getCell(2))) && StringUtils.isBlank(ImportUtil.getValue(xssfRow.getCell(3)))) {
							xssfRow.createCell(2);
							xssfRow.createCell(3);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(2));
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(3));
							flag = false;
						}
						if (!ImportUtil.checkRequired(ImportUtil.getValue(xssfRow.getCell(4)))) {
							xssfRow.createCell(4);
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(4));
							flag = false;
						} else if (!ImportUtil.checkWeight(ImportUtil.getValue(xssfRow.getCell(4)))) {
							ImportUtil.setStyle(xssfWorkbook, xssfRow.getCell(4));
							flag = false;
						}
					}

					if (xssfSheet.getLastRowNum() < 3) {
						flag = false;
						errorMsg = "导入文件数据为空,请下载模板重新导入";
					} else if (!flag && xssfSheet.getLastRowNum() >= 3) {
						File targetFile = File.createTempFile("customer-of-import-checked-" + System.currentTimeMillis(), ".xlsx");
						targetFile.deleteOnExit();
						xssfWorkbook.write(new FileOutputStream(targetFile));
						model.addAttribute("fileName", targetFile.getName());
					} else {

						//根据用户角色，判断是否合并
						List<ImportVO> voList = ImportUtil.readXlsx(xssfSheet, "public", UserUtils.getUser().getId());
						int userWeight = 40;
						String userFlag = UserUtils.getUser().getUserType();

						if ("1".equals(userFlag)) {
							userWeight = 90;
						} else if ("2".equals(userFlag)) {
							userWeight = 60;
						}

						//处理导入数据分组信息
						List<PotentialAdminGroup> adminGroupList = potentialAdminGroupService.findList(null);

						for (ImportVO vo : voList) {
							//管理员分组
							if (StringUtils.isNotBlank(realAdminGroupId)) {
								vo.setRealAdminGroupId(realAdminGroupId);
								//查询分组信息，检测分组是否删除，同时获取父级分组
								PotentialAdminGroup potentialAdminGroup = getPotentialAdminGroup(adminGroupList, realAdminGroupId);
								if (null != potentialAdminGroup && StringUtils.isNotBlank(potentialAdminGroup.getId())) {
									//顶级分组
									if (potentialAdminGroup.getParentId().equals("0")) {
										vo.setAdminGroup1Id(realAdminGroupId);
										vo.setHasAdminGroup("yes");
									} else { //第二级分组
										PotentialAdminGroup parentAdminGroup = getPotentialAdminGroup(adminGroupList, realAdminGroupId);
										if (parentAdminGroup.getParentId().equals("0")) {
											vo.setAdminGroup1Id(parentAdminGroup.getId());
											vo.setAdminGroup2Id(realAdminGroupId);
											vo.setHasAdminGroup("yes");
										} else {//第三级分组
											//管理员分组最多分为3级，因此本次查询出的数据为最顶级分组
											PotentialAdminGroup grandpaAdminGroup = getPotentialAdminGroup(adminGroupList, realAdminGroupId);
											vo.setAdminGroup1Id(grandpaAdminGroup.getId());
											vo.setAdminGroup2Id(parentAdminGroup.getId());
											vo.setAdminGroup3Id(realAdminGroupId);
											vo.setHasAdminGroup("yes");
										}
									}
								}
							}
						}

						successNum = voList.size();
						long saveBegin = System.currentTimeMillis();
						try {
							mergerNum = importService.save(voList, userWeight, true, "IMPORT");
						} catch (Exception e) {
							flag = false;
							errorMsg = "请检测导入的客户字段是否正确或者联系管理员";
							e.printStackTrace();
						}

						long saveEnd = System.currentTimeMillis();

						logger.info("客户管理>导入添加客户>导入保存合并信息时,处理" + successNum + "条数据,耗时:" + (saveEnd - saveBegin) / 1000 + "秒");
						logger.info("客户管理>导入添加客户>从导入开始到结束,共处理" + successNum + "条数据,共耗时:" + (saveEnd - begin) / 1000 + "秒");
					}
				} else {
					flag = false;
					errorMsg = "导入数据超过1万条,请将数据控制在1万条以内,再重新导入！！！";
				}

			} else {
				flag = false;
				errorMsg = "上传的附件文件不能超过8M！！！";
			}

		} else {
			flag = false;
			errorMsg = "导入文件格式错误,请下载模板重新导入";
		}

		model.addAttribute("successNum", successNum);
		model.addAttribute("mergerNum", mergerNum);
		model.addAttribute("flag", flag);
		model.addAttribute("errorMsg", errorMsg);

		return "modules/customer/potentialcustomer/potentialCustomerImportResult";
	}

	/**
	 * 获取管理员分组信息
	 * @return
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	private PotentialAdminGroup getPotentialAdminGroup(List<PotentialAdminGroup> adminGroupList, String realAdminGroupId) {

		for (PotentialAdminGroup group : adminGroupList) {
			if (realAdminGroupId.equals(group.getId())) {
				return group;
			}
		}
		return null;
	}


	/**
	 * 下载导入校验结果
	 * @return
	 * @throws Exception
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "import/checked" )
	public ResponseEntity<byte[]> importChecked(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {

		File templateFile = new File(System.getProperty("java.io.tmpdir") + File.separator + fileName);

		HttpHeaders headers = new HttpHeaders();
		//获取User-Agent
		String agent = request.getHeader("User-Agent");
		if (org.apache.commons.lang3.StringUtils.isNotBlank(agent) && agent.toLowerCase().contains("linux")) {
			//解决Linux系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入校验结果.xlsx".getBytes("UTF-8"), "ISO8859-1"));
		} else {
			//解决Windows系统浏览器乱码
			headers.setContentDispositionFormData("attachment", new String("客户基本信息导入校验结果.xlsx".getBytes("GBK"), "ISO8859-1"));
		}
		//导出office2010文件，后缀格式.xlsx
		headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(templateFile), headers, HttpStatus.CREATED);
	}

	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = {"list/private"} )
	public String privateList(PotentialCustomer potentialCustomer, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("sys_user_type", UserUtils.getUser().getUserType());
		return "modules/customer/potentialcustomer/privatePotentialCustomerAjaxList";
	}

	@RequiresPermissions ( "customer:potentialCustomer:view" )
	@RequestMapping ( value = "privateListAjaxData" )
	@ResponseBody
	public Page<PotentialCustomer> privateListAjaxData(PotentialCustomer potentialCustomer, HttpServletRequest request, HttpServletResponse response, Model model) {
		potentialCustomer.setRecordVisibilityRule("private");
		return potentialCustomerService.findPage(new Page<PotentialCustomer>(request, response), potentialCustomer);
	}

	/**
	 * 回收数据
	 * @param ids
	 * @return
	 * @author shishouyang
	 * @date 2015年8月28日 上午10:20:49
	 */
	@RequiresPermissions ( "customer:potentialCustomer:delete" )
	@RequestMapping ( value = "recover" )
	@ResponseBody
	public AjaxMessage recover(String[] ids) {
		AjaxMessage ajaxMessage = AjaxMessage.success();
		List<PotentialCustomer> customerList = new ArrayList<PotentialCustomer>();
		try {
			if (ids.length == 0) {
				ajaxMessage.makeError("请选择需要回收的数据");
				return ajaxMessage;
			}
			for (int i = 0; i < ids.length; i++) {
				PotentialCustomer customer = potentialCustomerService.get(ids[i]);
				customer.setExecutorId(null);//执行人ID
				customer.setExecutorName(null);
				customer.setDistStatus("UNDISTED");//分配状态
				customerList.add(customer);
			}
			//回收数据
			User user=UserUtils.getUser();
			importService.newRecover(user,customerList);
			ajaxMessage.setMessage("回收成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ajaxMessage.makeError("回收数据出现问题，请稍后再试");
		}
		return ajaxMessage;
	}


	/**
	 * 用户数据提交接口
	 * @param vo
	 * @throws Exception
	 * @author shishouyang
	 * @date 2015-08-24 11:29:12
	 */
	@RequestMapping ( value = "sealSave" )
	@ResponseBody
	public Map<String, Object> importSubmit(ImportVO vo) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		String flag = "ok";
		String message = "提交成功";
		String sourceFlag = "KNET";

		//数据验证
		if (StringUtils.isBlank(vo.getCorporationUrl())) {
			flag = "error1";
			message = "系统提交失败,保存客户信息出错,客户域名信息不存在";
			resultMap.put("flag", flag);
			resultMap.put("message", message);
			return resultMap;
		}
		if (StringUtils.isBlank(vo.getCorporationName())) {
			flag = "error2";
			message = "系统提交失败,保存客户信息出错,客户公司名称不存在";
			resultMap.put("flag", flag);
			resultMap.put("message", message);
			return resultMap;
		}
		if (StringUtils.isBlank(vo.getMobile()) && StringUtils.isBlank(vo.getTelephone())) {
			flag = "error2";
			message = "系统提交失败,保存客户信息出错,客户手机和电话信息必须存在一个";
			resultMap.put("flag", flag);
			resultMap.put("message", message);
			return resultMap;
		}

		//根据用户角色，判断是否合并
		List<ImportVO> voList = new ArrayList<ImportVO>();

		String sourceType = vo.getSourceType();
		if (StringUtils.isNotBlank(sourceType)) {
			if ("knet".equalsIgnoreCase(sourceType)) {
				sourceFlag = "KNET";
				vo.setWeight(80);//权重
			} else if ("logo".equalsIgnoreCase(sourceType)) {
				sourceFlag = "KNETL";
				vo.setWeight(80);//权重
			} else if ("edm".equalsIgnoreCase(sourceType)) {
				sourceFlag = "MAIL";
				vo.setWeight(70);//权重
			} else if ("bd".equalsIgnoreCase(sourceType)) {
				sourceFlag = "BD";
				vo.setWeight(70);//权重
			} else {
				sourceFlag = "SYSTEM";
				vo.setWeight(70);//权重
			}
		}

		vo.setVersion(Long.parseLong("0"));//版本
		vo.setDateCreated(new Date());//创建时间
		vo.setLastUpdated(new Date());//最后更新时间
		vo.setDistStatus("UNDISTED");//分配状态
		vo.setMergerNum(0);//合并数量
		vo.setMobileOrPc("pc");//设备来源
		vo.setNoReadMergerNum(0);//未读合并数量
		vo.setVisitNum(0);//回访次数
		vo.setRecordVisibilityRule("public");//公有私有
		vo.setVisibilityUserId(UserUtils.getUser().getId());//持有人ID
		vo.setDelFlag("0");//删除标识
		vo.setProvinceId(RegionUtils.getRegionId(vo.getProvinceName()));

		voList.add(vo);

		//系统提交用户权重设为100,不影响系统提交数据的权重
		int userWeight = 100;
		try {
			importService.save(voList, userWeight, true, sourceFlag);
		} catch (Exception e) {
			flag = "error5";
			message = "提交失败,保存客户信息出错";
			logger.error("系统提交失败,保存客户信息出错;客户信息:" + vo.toString());
		}

		resultMap.put("flag", flag);
		resultMap.put("message", message);
		return resultMap;
	}
}